package swingxrcp.framework.client.action;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;

import org.apache.http.entity.AbstractHttpEntity;

import swingxrcp.framework.util.serialize.Serializer;

public class SerializeEntity extends AbstractHttpEntity {

	private Serializer serializer;

    private Serializable object;

    public SerializeEntity(Serializer serializer, Serializable object) throws IOException {
        super();
        this.serializer = serializer;
        this.object = object;
    }

    public InputStream getContent() throws IOException, IllegalStateException {
    	ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(baos);
        out.writeObject(object);
        out.flush();
        return new ByteArrayInputStream(baos.toByteArray());
    }

    public long getContentLength() {
    	return -1;
    }

    public boolean isRepeatable() {
        return true;
    }

    public boolean isStreaming() {
        return true;
    }

    public void writeTo(OutputStream outstream) throws IOException {
        if (outstream == null)
            throw new IllegalArgumentException("Output stream may not be null");
        serializer.serialize(object, outstream);
    }

}
